//
//  EmoteSelectorView.m
//  MyChat
//
//  Created by Ansen on 15-2-18.
//  Copyright (c) 2015年 Ansen. All rights reserved.
//

#import "EmoteSelectorView.h"

static unichar emotechars[28] =
{
    0xe415, 0xe056, 0xe057, 0xe414, 0xe405, 0xe106, 0xe418,
    0xe417, 0xe40d, 0xe40a, 0xe404, 0xe105, 0xe409, 0xe40e,
    0xe402, 0xe108, 0xe403, 0xe058, 0xe407, 0xe401, 0xe416,
    0xe40c, 0xe406, 0xe413, 0xe411, 0xe412, 0xe410, 0xe059,
};

#define kRowCount   4
#define kColCount   7
#define kStartPoint CGPointMake(6, 20)
#define kButtonSize CGSizeMake(44, 44)

@implementation EmoteSelectorView

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = [UIColor lightGrayColor];
        
        [self setEmote];
    }
    return self;
}

-(void)setEmote
{
    
    NSMutableArray *array = [NSMutableArray array];
    
    for (NSInteger row = 0; row < kRowCount; row++) {
        for (int col = 0; col < kColCount; col++) {
            
            NSInteger index = row * kColCount + col;
            
            // 2. 创建按钮
            // 1) 实例化
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            // 2) 设置位置，自定义视图中没有使用AutoLayout，因此，可以使用setFrame
            NSInteger x = kStartPoint.x + col * kButtonSize.width;
            NSInteger y = kStartPoint.y + row * kButtonSize.height;
            
            [btn setFrame:CGRectMake(x, y, kButtonSize.width, kButtonSize.height)];
            
            btn.tag = index;
            
            // 4) 添加按钮监听方法
            [btn addTarget:self action:@selector(clickEmote:) forControlEvents:UIControlEventTouchUpInside];
            
            // 5) 添加到视图
            [self addSubview:btn];
            
            // 6) 添加到临时数组
            [array addObject:btn];
            
        }
    }
    
    // 遍历临时数组，设置按钮内容
    for (UIButton *btn in array) {
        
        if (btn.tag == 27) {
            // 最末尾的删除按钮，设置按钮图像
            UIImage *img = [UIImage imageNamed:@"DeleteEmoticonBtn"];
            UIImage *imgHL = [UIImage imageNamed:@"DeleteEmoticonBtnHL"];
            
            [btn setImage:img forState:UIControlStateNormal];
            [btn setImage:imgHL forState:UIControlStateHighlighted];
        }else{
            // 设置其他按钮的文字
            NSString *string = [self emoteStringWithIndex:btn.tag];
            [btn setTitle:string forState:UIControlStateNormal];
        }
    }
}

-(NSString *)emoteStringWithIndex:(NSInteger)index
{
    return [NSString stringWithFormat:@"%C",emotechars[index]];
}

#pragma mark - 表情按钮点击事件
- (void)clickEmote:(UIButton *)button
{
    NSString *str = [self emoteStringWithIndex:button.tag];
    if (button.tag != 27) {
        [_delegate emoteSelectorViewSelecteString:str];
    }else{
        [_delegate emoteSelectViewRemoverChar];
    }
}
@end
